package com.shenjies88.practice.reactor.thread;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * @author shenjies88
 * @since 2022/12/7/23:55
 */
public class WorkRunnable implements Runnable {

    private final SelectionKey selectionKey;

    public WorkRunnable(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }

    @Override
    public void run() {
        var channel = (SocketChannel) selectionKey.channel();
        var buffer = (ByteBuffer) selectionKey.attachment();
        try {
            int read = channel.read(buffer);
            if (read == -1) {
                channel.close();
                return;
            }
            while (read > 0) {
                buffer.flip();
                System.out.println(Thread.currentThread().getName() + " msg form client: " + new String(buffer.array()).trim());
                buffer.clear();
                read = channel.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("工作线程读取异常");
        }
    }
}
